package com.uyayo.oms.system.controller;

import com.uyayo.framework.common.annotation.MethodName;
import com.uyayo.framework.common.exception.CodeMultipleException;
import com.uyayo.framework.message.enums.ResultMsgEnum;
import com.uyayo.framework.message.model.Result;
import com.uyayo.framework.pagehelper.pojo.PageBean;
import com.uyayo.framework.pagehelper.pojo.PageResult;
import com.uyayo.oms.shiro.ShiroService;
import com.uyayo.oms.system.biz.ParamBiz;
import com.uyayo.oms.system.vo.SysPermissionInitVO;
import com.uyayo.system.authority.entity.SysUser;
import com.uyayo.system.config.entity.SysPermissionInit;
import com.uyayo.system.config.model.SysPermissionInitCondition;
import com.uyayo.system.config.service.SysPermissionInitService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.dozer.DozerBeanMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.stereotype.Controller;
import org.springframework.validation.Errors;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;


/**
 * 
 * Title: GroupController
 * Description:会员组的控制器
 * Company: www.uyayo.com
 *
 * @author 优雅哟.胡逢君
 * @date 2015-4-13下午4:03:35
 * @version 1.0
 */
@Controller
@RequestMapping("/oms/system/config/permission")
public class SysPermissionConfigController {

	private final SysPermissionInitService sysPermissionInitService;

	private final ShiroService shiroService;
	private final ParamBiz paramBiz;

	private  final MessageSource messageSource;

	private final DozerBeanMapper dozerBeanMapper;

	private final Logger logger = LoggerFactory.getLogger(this.getClass());

	@Autowired
	public SysPermissionConfigController(ParamBiz paramBiz, SysPermissionInitService sysPermissionInitService, ShiroService shiroService, MessageSource messageSource, DozerBeanMapper dozerBeanMapper) {
		this.paramBiz = paramBiz;
		this.sysPermissionInitService = sysPermissionInitService;
		this.shiroService = shiroService;
		this.messageSource = messageSource;
		this.dozerBeanMapper = dozerBeanMapper;
	}

	@RequestMapping(value="index",method=RequestMethod.GET)
	@MethodName(value="系统管理->配置管理->权限配置")
	@RequiresPermissions("system:config:permission:index")
	public String index() throws Exception {
		return paramBiz.getManagerTemplatesPrefix()+"system/config/permission/index";
	}
	
	@ResponseBody
	@RequestMapping(value="query",method=RequestMethod.GET)
	@MethodName(value="系统管理->配置管理->权限配置->查询列表",type=2)
	@RequiresPermissions("system:config:permission:query")
	public PageResult<SysPermissionInit> query(@RequestParam(value = "offset",required = false, defaultValue = "1") Integer start, //第多少行之后开始
											   @RequestParam(value = "limit", required = false, defaultValue = "10") Integer pageSize,
											   String sort, String order, HttpServletRequest request, SysPermissionInitCondition sysPermissionInitCondition) throws Exception {
		PageBean<SysPermissionInit> pageBean=new PageBean<>();
		try {
			pageBean.setPageCurrent((start / pageSize) + 1);
			pageBean.setPageSize(pageSize);
			pageBean.setOrderField(sort);
			pageBean.setOrderDirection(order);
			pageBean = sysPermissionInitService.selectSysPermissionInit(pageBean,sysPermissionInitCondition);
		} catch (Exception e) {
			String message = messageSource.getMessage(ResultMsgEnum.INTERNAL_SERVER_ERROR.getKey(),new Object[]{}, request.getLocale());
			logger.error(message,e);
		}
		PageResult<SysPermissionInit> pageResult = new PageResult<>();
		pageResult.setRows(pageBean.getList());
		pageResult.setTotal(pageBean.getTotalCount());
		return pageResult;
		
	}
	
	/**
	 * 进入添加页面
	 * @param modelAndView ModelAndView
	 * @return ModelAndView
	 */
	@RequestMapping(value = "add", method = RequestMethod.GET)
	@RequiresPermissions("system:config:permission:create")
	public ModelAndView add(ModelAndView modelAndView) {
		
		modelAndView.setViewName(paramBiz.getManagerTemplatesPrefix()+"system/config/permission/add");
		return modelAndView;
	}
	
	/**
	 * 新建一个服务器记录
	 */
	@ResponseBody
	@RequestMapping(value = "add", method = RequestMethod.POST)
	@RequiresPermissions("system:config:permission:create")
	@MethodName(value="系统管理->配置管理->权限配置->保存",type=2)
	synchronized public Result add(HttpServletRequest request, @Validated SysPermissionInitVO sysPermissionInitVO , Errors errors) {
		try {
			if (errors.hasErrors()) {
				return Result.errorAndMsg(errors.getFieldError().getDefaultMessage());
		    }
			Subject subject = SecurityUtils.getSubject();
			SysUser sysUser = (SysUser) subject.getPrincipal();
			SysPermissionInit sysPermissionInit = dozerBeanMapper.map(sysPermissionInitVO,SysPermissionInit.class);
			sysPermissionInit.setCreateTime(new Date());
			sysPermissionInit.setCreateBy(sysUser.getLoginname());
			sysPermissionInitService.saveSysPermissionInit(sysPermissionInit);
		}catch (CodeMultipleException e){
			String message = messageSource.getMessage(ResultMsgEnum.CODE_MULTIPLE.getKey(),new Object[]{}, request.getLocale());
			logger.info(message,e.getMessage());
			return Result.error(ResultMsgEnum.CODE_MULTIPLE.code(),message);
		}  catch (Exception e) {
			String message = messageSource.getMessage(ResultMsgEnum.INTERNAL_SERVER_ERROR.getKey(),new Object[]{}, request.getLocale());
			logger.error(message,e);
			return Result.error(ResultMsgEnum.INTERNAL_SERVER_ERROR.code(),message);
		}
		String message = messageSource.getMessage(ResultMsgEnum.SAVE_SUCCESS.getKey(),new Object[]{}, request.getLocale());
		return Result.success(ResultMsgEnum.SAVE_SUCCESS.code(),message);
	}
	
	/**
	 * 进入服务器记录查看页面
	 */
	@RequestMapping(value = "view", method = RequestMethod.GET)
	@MethodName(value="系统管理->配置管理->权限配置->查看",type=2)
	@RequiresPermissions("system:config:permission:view")
	public ModelAndView show(ModelAndView modelAndView,HttpServletRequest request,Long id) {
		SysPermissionInit sysPermissionInit = new SysPermissionInit();
		try {
			sysPermissionInit = sysPermissionInitService.getSysPermissionInitById(id);
		} catch (Exception e) {
			String message = messageSource.getMessage(ResultMsgEnum.INTERNAL_SERVER_ERROR.getKey(),new Object[]{}, request.getLocale());
			logger.error(message,e);
		}
		modelAndView.addObject("sysPermissionInit",sysPermissionInit);
		modelAndView.setViewName(paramBiz.getManagerTemplatesPrefix()+"system/config/permission/view");
		return modelAndView;
	}

	/**
	 * 进入角色修改页面
	 */
	@RequestMapping(value = "update", method = RequestMethod.GET)
	@RequiresPermissions("system:config:permission:update")
	public ModelAndView update(ModelAndView modelAndView,HttpServletRequest request,Long id) {
		SysPermissionInit sysPermissionInit = new SysPermissionInit();
		try {
			sysPermissionInit = sysPermissionInitService.getSysPermissionInitById(id);
		} catch (Exception e) {
			String message = messageSource.getMessage(ResultMsgEnum.INTERNAL_SERVER_ERROR.getKey(),new Object[]{}, request.getLocale());
			logger.error(message,e);
		}
		modelAndView.addObject("sysPermissionInit",sysPermissionInit);
		modelAndView.setViewName(paramBiz.getManagerTemplatesPrefix()+"system/config/permission/update");
		return modelAndView;
	}
	
	/**
	 * 修改
	 */
	@ResponseBody
	@RequestMapping(value = "update", method = RequestMethod.POST)
	@RequiresPermissions("system:config:permission:update")
	@MethodName(value="系统管理->配置管理->权限配置->修改",type=2)
	synchronized public Result update(HttpServletRequest request,@Validated SysPermissionInitVO sysPermissionInitVO , Errors errors) {
		try {
			if (errors.hasErrors()) {
				return Result.errorAndMsg(errors.getFieldError().getDefaultMessage());
		    }
			Subject subject = SecurityUtils.getSubject();
			SysUser sysUser = (SysUser) subject.getPrincipal();
			SysPermissionInit sysPermissionInit = dozerBeanMapper.map(sysPermissionInitVO,SysPermissionInit.class);
			sysPermissionInit.setUpdateTime(new Date());
			sysPermissionInit.setUpdateBy(sysUser.getLoginname());
			sysPermissionInitService.updateSysPermissionInit(sysPermissionInit);
		} catch (CodeMultipleException e){
			String message = messageSource.getMessage(ResultMsgEnum.CODE_MULTIPLE.getKey(),new Object[]{}, request.getLocale());
			logger.info(message,e.getMessage());
			return Result.error(ResultMsgEnum.CODE_MULTIPLE.code(),message);
		}  catch (Exception e) {
			String message = messageSource.getMessage(ResultMsgEnum.INTERNAL_SERVER_ERROR.getKey(),new Object[]{}, request.getLocale());
			logger.error(message,e);
			return Result.error(ResultMsgEnum.INTERNAL_SERVER_ERROR.code(),message);
		}
		String message = messageSource.getMessage(ResultMsgEnum.SAVE_SUCCESS.getKey(),new Object[]{}, request.getLocale());
		return Result.success(ResultMsgEnum.SAVE_SUCCESS.code(),message);
	}

	/**
	 * 删除记录
	 */
	@ResponseBody
	@RequiresPermissions("system:config:permission:delete")
	@RequestMapping(value="delete",method=RequestMethod.DELETE)
	@MethodName(value="系统管理->配置管理->权限配置->删除",type=2)
	public Result delete(HttpServletRequest request, Long id) {
		try {
			if (id==null) {
				String message = messageSource.getMessage(ResultMsgEnum.PARAMETER_ERROR.getKey(),new Object[]{}, request.getLocale());
				logger.error(message);
				return Result.error(ResultMsgEnum.PARAMETER_ERROR.code(),message);
			}
			int deleteCount = sysPermissionInitService.deleteSysPermissionInitById(id);
			if(deleteCount<=0){
				String message = messageSource.getMessage(ResultMsgEnum.DELETE_FAIL.getKey(),new Object[]{}, request.getLocale());
				logger.error(message);
				return Result.error(ResultMsgEnum.DELETE_FAIL.code(),message);
			}
		} catch(Exception e) {
			String message = messageSource.getMessage(ResultMsgEnum.INTERNAL_SERVER_ERROR.getKey(),new Object[]{}, request.getLocale());
			logger.error(message,e);
			return Result.error(ResultMsgEnum.INTERNAL_SERVER_ERROR.code(),message);
		}
		String message = messageSource.getMessage(ResultMsgEnum.DELETE_SUCCESS.getKey(),new Object[]{}, request.getLocale());
		return Result.success(ResultMsgEnum.DELETE_SUCCESS.code(),message);

	}

	/**
	 * 初始化
	 */
	@ResponseBody
	@RequiresPermissions("system:config:permission:init")
	@RequestMapping(value="init",method=RequestMethod.GET)
	public Result init(HttpServletRequest request) {
		try {
			shiroService.updatePermission();
		} catch(Exception e) {
			String message = messageSource.getMessage(ResultMsgEnum.INTERNAL_SERVER_ERROR.getKey(),new Object[]{}, request.getLocale());
			logger.error(message,e);
			return Result.error(ResultMsgEnum.INTERNAL_SERVER_ERROR.code(),message);
		}
		String message = messageSource.getMessage(ResultMsgEnum.INIT_SUCCESS.getKey(),new Object[]{}, request.getLocale());
		return Result.success(ResultMsgEnum.INIT_SUCCESS.code(),message);	}
}
